<?php

namespace app\technician\controller;

use app\common\controller\Api;
use app\common\model\StoreWifi;
use think\Db;
use Carbon\Carbon;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Work extends Home
{
    public $noNeedLogin = [];


    /**
     * 检测当日打卡状态
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check(){
        if($this->request->isPost()){
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if(empty($getData['time']) || !isset($getData['time'])){
                $this->result('缺少参数', '', 204);
            }
            $time = explode('-',$getData['time']);
            $week = Carbon::create($time[0], $time[1], $time[2])->dayOfWeekIso;
            //获取用户每天打卡次数
            $workId = Db::name('qt_post_work')->where('post_id',$userInfo['post_id'])->value('work_id');
            $workRes = Db::name('qt_work')->where('id',$workId)->find();
            //查询周一到周日的打卡时间
            $workNum = Db::name('qt_work_num')
                ->where('work_id',$workRes['id'])
                ->where('week',$week)
                ->order('week asc')
                ->group('week')
                ->find();
            //查询今日的打卡次数
            $count = Db::name('qt_work_log')
                ->where(['user_id'=>$userInfo['id'],'day'=>$getData['time'],'week'=>$week])
                ->whereIn('type','1,2,3,5,7,9')
                ->count();
            //正常上班
            if($workNum['type'] == '1'){
                if($count == $workRes['work_num']){
                    $result['status'] = '1'; //打卡正常
                    $result['data'] = []; //打卡正常
                }else{
                    $data = Db::name('qt_work_log')
                        ->field('id,created_time')
                        ->where(['user_id'=>$userInfo['id'],'day'=>$getData['time'],'week'=>$week])
                        ->whereIn('type','0,4')
                        ->select();
                    $result['status'] = '0'; //打卡异常
                    $result['data'] = $data; //打卡异常
                }
            }else{
                //休息日
                $result['status'] = '1'; //打卡正常
                $result['data'] = []; //打卡正常
            }
            $this->result('请求成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);

    }


    /**
     * 当天打卡记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function work_list(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $time =  strtotime($getData['time']);
            //查询用户打卡记录
            $data = Db::name('qt_work_log')
                ->where(['user_id'=>$this->userInfo['id'],'store_id'=>$this->store_id,'day'=>$time])
                ->order('id desc')
                ->select();
            $this->result('获取成功', $data, 200);
        }
    }




    /**
     * 获取用户打卡时间
     */
    public function work_config()
    {
        if ($this->request->isPost()) {
            $time = strtotime(date('Y-m-d'));
            //查询用户打卡记录
            $workLog = Db::name('qt_work_log')
                ->where(['user_id'=>$this->userInfo['id'],'store_id'=>$this->store_id,'day'=>$time])
                ->order('id desc')
                ->find();
            if(empty($workLog)){
                $result['work_status'] = '1';//上班卡
            }elseif($workLog['work_type'] == '1'){
                $result['work_status'] = '2';//下班卡
                $result['data'] = $workLog;
            }else{
                $result['work_status'] = '1';//上班卡
            }
            $this->result('获取成功', $result, 200);
        }
    }


    /**
     * 打卡
     */
    public function clock(){
        if ($this->request->isPost()) {
            //打卡位置
            $getData = $this->request->post();
            if(empty($getData['work_status'])){
                $this->result('缺少参数', '', 204);
            }
//            $userWifi = Db::name('qt_store_wifi')->where('store_id',$this->store_id)->column('wifi');
//            if(in_array($getData['wifi'],$userWifi)){
                $insertData  = $this->getWorkData($this->userInfo,time(),$getData['work_status']);
                $insertData['lat'] = $getData['lat'];
                $insertData['lon'] = $getData['lon'];
                $save = Db::name('qt_work_log')->insert($insertData);
                if($getData['work_status'] == '1'){
                    Db::name('qt_users')->where(['id'=>$this->userInfo['id']])->update(['work_status'=>'1']);
                }
                if($getData['work_status'] == '2'){
                    Db::name('qt_users')->where(['id'=>$this->userInfo['id']])->update(['work_status'=>'2']);
                }
                $this->result('打卡成功', '', 200);

//            }else{
//                $this->result('无效的无线网', '', 204);
//            }


        }
        $this->result('无效的请求', '', 204);
    }


    /**
     *
     * 获取用户打卡时间
     * @param $userInfo
     * @param $time
     * @param $workStatus
     * @return array
     */
    public function getWorkData($userInfo,$time,$workStatus){
        $week = Carbon::now()->dayOfWeekIso;//星期
        $insertData['user_id'] = $userInfo['id'];
        $insertData['store_id'] = $userInfo['store_id'];
        $insertData['week'] =$week;
        $insertData['day'] =strtotime(date('Y-m-d')) ;
        $insertData['work_type'] =$workStatus;
        $insertData['created_time'] = $time;
        $insertData['type'] = '1';
        return $insertData;
    }

    /**
     * 获取无线网数据列表
     */
    public function wifiList(){
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $data = Db::name('qt_store_wifi')
                ->field('id,wifi,mac')
                ->where(['store_id'=>$userInfo['store_id']])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取无线网数据列表
     */
    public function wifiAdd(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['wifi']) || empty($getData['wifi'])){
                $this->result('缺少参数', '', 204);
            }
            if(!isset($getData['mac']) || empty($getData['mac'])){
                $this->result('缺少参数', '', 204);
            }
            $getData['created_time'] = time();
            $getData['store_id'] = $this->userInfo['store_id'];
            $data = Db::name('qt_store_wifi')->insert($getData);
            if($data){
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取无线网数据列表
     */
    public function wifiDel(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['id']) || empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $del = Db::name('qt_store_wifi')->where('id',$getData['id'])->delete();
            if($del){
                $this->result('删除成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 打卡统计个人
     */
    public function statistics()
    {
        if ($this->request->isPost()) {
            //打卡时间
            $getData = $this->request->post();

            if(empty($getData['start_time'])){
                $this->result('缺少参数','',204);
            }
            //月统计
            $startDay =  $getData['start_time'].'-01';
            $time = explode('-',$getData['start_time']);
            $endDay = Carbon::create($time[0], $time[1])->endOfMonth()->toDateTimeString();
            $nowTime = date('Y-m-d');
            if($nowTime < $endDay){
                $endDay = $nowTime;
            }
            //列出这周的每一天日期
            $userInfo = $this->userInfo;
            $workId = Db::name('qt_post_work')->where('post_id',$userInfo['post_id'])->value('work_id');
            //获取用户每天打卡次数
            $workRes = Db::name('qt_work')->where('id',$workId)->find();
            //查询周一到周日的打卡时间
            $days = $this->getDateFromRange($startDay,$endDay);
            $workDay = 0;
            foreach ($days as $key=>$value){
                //查询今日的打卡次数
                $count = Db::name('qt_work_log')
                    ->where(['user_id'=>$userInfo['id'],'day'=>$value])
                    ->whereIn('type','1,3,5')
                    ->count();
                $result['data'][$key]['time'] = $value;
                if($count == $workRes['work_num']){
                    $result['data'][$key]['status'] = '1'; //打卡正常
                }else{
                    $result['data'][$key]['status'] = '0'; //打卡异常
                }
                $workDay ++;
            }
            $this->result('查询成功',$result,200);
        }
    }

    /**
     * 获取门店wifi列表
     */
    public function get_wifi_list(){
        if ($this->request->isPost()) {
            $data = StoreWifi::field('id,wifi,mac')->where(['store_id'=>$this->userInfo['store_id']])->select();
            $this->result('查询成功',$data,200);
        }
    }


    /**
     * 获取指定日期段内每一天的日期
     * @param  Date  $startdate 开始日期
     * @param  Date  $enddate   结束日期
     * @return Array
     */
    function getDateFromRange($startdate, $enddate){

        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp)/86400+1;

        // 保存每天日期
        $date = array();

        for($i=0; $i<$days; $i++){
            $date[] = date('Y-m-d', $stimestamp+(86400*$i));
        }
        return $date;
    }




}
